#
# fusion.core.identity
#
# Copyright 2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Public Keys / Key Pairs

>>> identity = generate()
>>> sig = identity.sign('Testing...')
>>> identity.verify('Testing...', sig)
True
>>> identity.verify('testing...', sig)
False

>>> PUBLIC = identity.encode_public()
>>> PRIVATE = identity.encode_private()
>>> len(PUBLIC) < len(PRIVATE)
True

>>> public = decode_identity(PUBLIC)
>>> private = decode_identity(PRIVATE)

>>> public.has_private()
False
>>> private.has_private()
True

>>> sig = private.sign('Testing...')
>>> SIG = sig.encode()
>>> sig = decode_signature(SIG)
>>> public.verify('Testing...', sig)
True

>>> public.encode_public() == PUBLIC
True
>>> private.encode_private() == PRIVATE
True
>>> sig.encode() == SIG
True

>>> identity.fingerprint == private.fingerprint
True
>>> identity.fingerprint == public.fingerprint
True
"""

from hashlib import sha1
from os import urandom
from binascii import hexlify

from Crypto.Util.number import bytes_to_long, long_to_bytes
from fusion.lib.sexp import encode, decode
from fusion.core.signature import Signature, decode_signature

class Identity(object):
    def __init__(self, type, key):
        self.type = type
        self.key = key           # pycrypto key object
        self._hash = None        # cached value

    @property
    def fingerprint(self):
        return hexlify(self.digest())

    def digest(self):
        if self._hash is None:
            sexp = self.encode_public()
            self._hash = sha1(sexp).digest()

        return self._hash

    def sign(self, string):
        if self.type == 'rsa-pycrypto':
            sig = self.key.sign(string, '')
        else:
            raise NotImplementedError

        return Signature(self.type, self.digest(), sig)

    def verify(self, string, signature):
        if self.type != signature.type:
            raise ValueError

        if self.digest() != signature.fp:
            return False

        try:
            return bool(self.key.verify(string, signature.data))
        except Exception:
            # Verifying a bad signature can raise a pycrypto error:
            # "Plaintext too large".
            return False

    def size(self):
        return self.key.size()

    def strength(self):
        # The pycrypto documentation recommends 512 bits for RSA and
        # 768 bits for ElGamal or DSA, for low-security commercial use.
        if self.type == 'rsa-pycrypto':
            recommendation = 512
        else:
            raise NotImplementedError

        return float(self.size() + 1) / recommendation

    def encode_public(self):
        data = map(long_to_bytes, _key_to_tuple(self.key.publickey()))
        return encode([self.type] + data)

    def encode_private(self):
        # Encode the private key too if present.
        data = map(long_to_bytes, _key_to_tuple(self.key))
        return encode([self.type] + data)

    def has_private(self):
        return bool(self.key.has_private())

def generate(type='rsa-pycrypto', size=None):
    if type == 'rsa-pycrypto':
        from Crypto.PublicKey import RSA
        if size is None:
            size = 512
        key = RSA.generate(size, urandom)
    else:
        raise NotImplementedError

    return Identity(type, key)

def decode_identity(string):
    parts = decode(string)
    if len(parts) < 2 or not all(isinstance(part, str) for part in parts):
        raise ValueError
    type, data = parts[0], parts[1:]
    data = tuple(map(bytes_to_long, data))

    if type == 'rsa-pycrypto':
        from Crypto.PublicKey.RSA import construct
        key = construct(data)
    else:
        raise ValueError('Identity to be decoded has unknown type "%s".' % type)

    identity = Identity(type, key)
    if identity.encode_private() != string:
        raise ValueError        # Reject noncanonical encodings.
    return identity

def _key_to_tuple(key):
    def gen(key):
        for name in key.keydata:
            if not hasattr(key, name):
                break
            yield getattr(key, name)

    return tuple(gen(key))

if __name__ == '__main__':
    import doctest
    doctest.testmod()
